package isv

import (
    "crypto/hmac"
	"crypto/sha1"
	"encoding/hex"
	//"fmt"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/misc"
	"github.com/astaxie/beego/orm"
	"github.com/satori/go.uuid"
)

type Manager struct {
    ManagerId       int64     `orm:"column(manager_id);pk;auto" json:"manager_id" form:"manager_id"`
	CreatedAt       time.Time `orm:"auto_now_add;type(datetime);column(created_at)" json:"created_at" form:"-"`     
	UpdatedAt       time.Time `orm:"auto_now;type(datetime);column(updated_at)" json:"updated_at" form:"-"`  
	UserName        string    `orm:"column(user_name);unique;size(45)" json:"user_name" form:"user_name"`
	Password        string    `orm:"-" json:"-" form:"password"`
	PasswordConfirm string    `orm:"-" json:"-" form:"password_confirm"`
	PasswordHashed  string    `orm:"column(password_hashed)" json:"-"`
	Salt            string    `orm:"column(salt)" json:"-"`
	WeixinId        string    `orm:"null;column(weixin_id)" json:"weixin_id,omitempty" form:"weixin_id"`
}

func init() {
	orm.RegisterModel(new(Manager))
}

// 对用户密码进行加“盐”的加密处理
func EncryptPassword(salt, password string) string {
	h := hmac.New(sha1.New, []byte(salt))
	h.Write([]byte(password))
	return hex.EncodeToString(h.Sum(nil))
}

//创建超级管理员
func CreateAdminUser(manager *Manager) (user_id int64, err error) {
	manager.Salt = uuid.NewV4().String()
	if manager.Password == "" {
		manager.Password = strings.ToLower(manager.UserName)
	}
	manager.PasswordHashed = EncryptPassword(manager.Salt, manager.Password)
	o := models.GetDefaultDB()
	i, err := o.Insert(manager)
	user_id = i
	return
}

// 如果没有记录，则返回：err: no row found
func GetManagerByUsername(username string) (manager *Manager, err error) {
	o := models.GetDefaultDB()
	manager = &Manager{UserName:username}   //多个的话,read中需要指明列
	if err = o.Read(manager,"Username"); err != nil {
		return manager, err
	}
	return manager, nil
}

func GetManagerById(uid int64) (manager *Manager, err error) {
	o := models.GetDefaultDB()
	manager = &Manager{ManagerId:uid}  
	if err = o.Read(manager); err != nil {
		return manager, err
	}
	return
}

//更新用户密码
func UpdateManagerPasswd(manager *Manager) (err error) {
	if len(manager.Password) == 0 {
		return nil
	}
	manager.PasswordHashed = EncryptPassword(manager.Salt, manager.Password)
	o := models.GetDefaultDB()
	_, err = o.Update(manager, "password_hashed")
	return
}

func InitDefaultManager(name, password string) (int64, error) {
	if oldManager, err := GetManagerByUsername(name); err == nil {
	    return oldManager.ManagerId, nil
	}
	uid, _ := misc.GetUserNo()
	manager := Manager{UserName:name,Password:password}
	_ ,err := CreateAdminUser(&manager)
	if err != nil {
	    return 0, err
	}
	return uid, nil
}
